package org.example.controller;

import cn.hutool.core.util.StrUtil;
import org.example.common.AuthAccess;
import org.example.common.Result;
import org.example.entity.User;
import org.example.service.JiaoyanmaService;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
public class WebController {
    @Autowired
    JiaoyanmaService jiaoyanmaService;
    @Resource
    UserService userService;

    @AuthAccess
    @GetMapping("/")
    public Result hello() {return Result.success("success");}

    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        if(StrUtil.isBlank(user.getUsername()) || StrUtil.isBlank(user.getPassword())) {
            return  Result.error("数据输入不合法");
        }
        user = userService.login(user);
        return Result.success(user);
    }

    @AuthAccess
    @PostMapping("/register")
    public Result register(@RequestParam("verificationCode") String verificationCode,@RequestBody User user) {

if(!user.getRole().equals("学生")){
        if (!verificationCode.equals(null) && jiaoyanmaService.slect(verificationCode)==null) {
            return Result.error("校验码错误");
        }else {
            user = userService.register(user);
            return Result.success(user);}
}else {
        user = userService.register(user);
        return Result.success(user);}
    }

//    重置密码
    @AuthAccess
    @PutMapping("/password")
    public Result password(@RequestBody User user) {
        if (StrUtil.isBlank(user.getUsername()) || StrUtil.isBlank(user.getPhone()) ) {
            return Result.error("数据输入不合法");
        }
        userService.resetPassword(user);
        return Result.success();
    }
}
